package com.baizhi.sync2;

/**
 * 银行账户
 */
public class Account {
    private String cardId;
    private double money; //账户余额

    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }



    public  void drawMoney(double money){
        //获取谁在刷这张卡
        String name = Thread.currentThread().getName();
        //花钱，如果余额大于要花的钱才能让花，
        //这个方法中真正让数据混乱的不是方法，而是对余额和花费的判断 所以，我们可以把这一段核心代码用syncronized(){} 同步代码块包裹起来

      synchronized (this){
          if(this.money > money){
              System.out.println(name + "花费了" + money);
              //更新余额
              this.money -= money;
              System.out.println(name + "花费后余额："+this.money);
          }else{
              System.out.println(name + "来取钱，余额不足");
          }
      }


    }


    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "cardId='" + cardId + '\'' +
                ", money=" + money +
                '}';
    }
}
